package com.browser.devtools;

import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ElementsPanel {
    private final BorderPane content;
    private final TreeView<String> elementTree;

    public ElementsPanel() {
        this.content = new BorderPane();
        this.elementTree = new TreeView<>();
        
        initializeUI();
    }

    private void initializeUI() {
        content.setCenter(elementTree);
    }

    public void updateDOM(Document document) {
        TreeItem<String> root = createTreeItem(document.getDocumentElement());
        elementTree.setRoot(root);
    }

    private TreeItem<String> createTreeItem(Node node) {
        TreeItem<String> item = new TreeItem<>(getNodeRepresentation(node));
        
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                item.getChildren().add(createTreeItem(child));
            }
        }
        
        return item;
    }

    private String getNodeRepresentation(Node node) {
        return node.getNodeName() + getNodeAttributes(node);
    }

    private String getNodeAttributes(Node node) {
        StringBuilder attrs = new StringBuilder();
        if (node.hasAttributes()) {
            for (int i = 0; i < node.getAttributes().getLength(); i++) {
                Node attr = node.getAttributes().item(i);
                attrs.append(" ").append(attr.getNodeName())
                     .append("=\"").append(attr.getNodeValue()).append("\"");
            }
        }
        return attrs.toString();
    }

    public BorderPane getContent() {
        return content;
    }
} 